import platform

# 从BaseManager继承的QueueManager:
import facade
from xjlibrary.mprocesspoll.process_distributed.BaseTask import BaseTask
from xjlibrary.network.MyIP import get_local_ip, GetLocalIPByPrefix
from xjlibrary.our_file_dir import BaseDir

curPath = BaseDir.get_file_dir_absolute(__file__)
configfile = BaseDir.get_new_path(curPath, "db.ini")


class SendTask(BaseTask):
    def __init__(self):
        super().__init__()
        sysstr = platform.system()
        if sysstr == "Windows":
            self.ip = GetLocalIPByPrefix("192.168.")
        else:
            self.ip = get_local_ip("enp2s0")
        self.port = 5000
        self.init_send(self.ip, self.port)


class SelectTask(object):
    def __init__(self):
        self.logger = facade.get_streamlogger()
        self.mysqlutils = facade.MysqlUtiles(configfile,
                                             "db",
                                             logger=self.logger)

    def createdb3(self):
        self.db3 = facade.Sqlite3Utiles(logger=self.logger). \
            Sqlite3DBConnectFromFilePath("./inputs.db3",
                                         encoding="utf-8")

        sql = """CREATE TABLE IF NOT EXISTS "article" ("rawid" text(100) NOT NULL,"stat" integer(20) NOT NULL DEFAULT 0,PRIMARY KEY ("rawid"));"""
        self.db3.ExeSqlliteSql(sql)

    def selectDB(self):
        sql = "select rawid from article where stat=0 limit 10000"
        rows = self.db3.SelectFromSqlliteFetchall(sql)
        return rows

    def dealsql(self, Lists):
        num = len(Lists)
        if num != 0:
            if num == 1:
                Lists.append("test")
            sql = "update article set stat=1 where rawid in {}".format(tuple(Lists))
            self.db3.ExeSqlliteSql(sql)


if __name__ == "__main__":
    sendtask = SendTask()
    select = SelectTask()
    select.createdb3()
    sendtask.start()
    sendtask.set_task_result_obj()
    while True:
        if sendtask.task.qsize() != 0:
            if sendtask.result.qsize() != 0:
                Lists = []
                for i in range(1, sendtask.result.qsize() + 1):
                    rawid = sendtask.result.get()
                    Lists.append(rawid)
                select.dealsql(Lists)
            print("send task num is:" + str(sendtask.task.qsize()))
        else:
            rows = select.selectDB()
            if rows:
                for row in rows:
                    if sendtask.task.full():
                        if sendtask.result.qsize() != 0:
                            Lists = []
                            for i in range(1, sendtask.result.qsize() + 1):
                                rawid = sendtask.result.get()
                                Lists.append(rawid)
                            select.dealsql(Lists)
                    sendtask.set_task(row[0])
